package com.begye.smartloan.apptest.detailbefore

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtDetailPBeforeBinding
import com.begye.smartloan.apptest.donotleavepage.DoNotLeavePageActivity
import com.begye.smartloan.apptest.gongong.YongHuJiDingYiViewModel
import com.begye.smartloan.apptest.homebefore.HomeBeforeActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.tool.SpTool
import com.begye.smartloan.apptest.tool.addTouch
import com.google.android.material.slider.Slider
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.toNextActivity
import java.util.Timer
import java.util.TimerTask


@SuppressLint("CustomWelcomeScreen")
class DetailBeforeActivity : AppCompatActivity() {

    companion object {
        const val GUIDE_FLAG = "GUIDE_FLAG"
    }

    private lateinit var _binding: AtDetailPBeforeBinding
    private var _guideTimer = Timer()

    private val _yongHuJiDingYiViewModel by lazy {
        ViewModelProvider(this)[YongHuJiDingYiViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtDetailPBeforeBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
        configUIData()
    }


    private fun configYongHuLiuChengState() {

        _yongHuJiDingYiViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuJiDingYiViewModel.onCheckYongHuDataLiveData.observe(this) {
            it?.let { result ->
                val remainJinEFormat = result.optString("remainJinEFormat", "")
                val minJinEFormat = result.optString("minJinEFormat", "")
                val sliderJinEFormat = result.optString("sliderJinEFormat", "")

                _binding.atDetailBeforeMaxValue.text = sliderJinEFormat
                _binding.atDetailBeforeGuideMaxValue.text = sliderJinEFormat

                _binding.atDetailBeforeSliderMin.text = minJinEFormat
                _binding.atDetailBeforeSliderMax.text = remainJinEFormat

                _binding.atDetailBeforeGuideSliderMin.text = minJinEFormat
                _binding.atDetailBeforeGuideSliderMax.text = remainJinEFormat

                updateCommitUIState()

                if (SpTool.get(GUIDE_FLAG) != "YES") {
                    _binding.atDetailBeforeTopGuideBg.visibility = View.VISIBLE
                    setCutDownStart()
                }
            }
        }

        _yongHuJiDingYiViewModel.onSliderChangedLiveData.observe(this) {
            it?.let { result ->
                _binding.atDetailBeforeMaxValue.text = result
                _binding.atDetailBeforeGuideMaxValue.text = result

                updateCommitUIState()
            }
        }

        _yongHuJiDingYiViewModel.onCalChangedLiveData.observe(this) {
            it?.let { result ->
                _binding.atDetailBeforeDisJinE.text = result.optString("disJinE")
                _binding.atDetailBeforeDisWithJinE.text = result.optString("disWithJinE")
                _binding.atDetailBeforeDisFee.text = result.optString("disFee")

                _binding.atDetailBeforeRpJinE.text = result.optString("rpJinE")
                _binding.atDetailBeforeRpWithJinE.text = result.optString("rpWithJinE")
                _binding.atDetailBeforeRpFee.text = result.optString("rpFee")
            }
        }

        _yongHuJiDingYiViewModel.onShenQingSuccessfulDataLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = DoNotLeavePageActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }
    }

    private fun configUIState() {

    }

    private fun configUIEvent() {
        try {
            _binding.atDetailBeforeNav.initConfig(
                text = "",
                leftResId = R.drawable.dres_5,
                rightResId = R.drawable.dres_4
            ) {
                if (0 == it) {
                    toNextActivity(
                        activity = HomeBeforeActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                } else if (1 == it) {
                    val dialog = KeFuDialogFragment()
                    dialog.showNow(supportFragmentManager, "kefu")
                }
            }

            val thumbDrawable = ContextCompat.getDrawable(this, R.drawable.dres_31)
            thumbDrawable?.let {
                _binding.atDetailBeforeSlider.setCustomThumbDrawable(it)
                _binding.atDetailBeforeGuideSlider.setCustomThumbDrawable(it)
            }

            _binding.atDetailBeforeGuideOk.setOnClickListener {
                _guideTimer.cancel()
                _binding.atDetailBeforeTopGuideBg.visibility = View.GONE
                SpTool.save(GUIDE_FLAG, "YES")
            }

            _binding.atDetailBeforeSlider.addOnChangeListener { _, process, _ ->
                _yongHuJiDingYiViewModel.calSliderChanged(process, true)
            }

            _binding.atDetailBeforeSlider.addOnSliderTouchListener(object :
                Slider.OnSliderTouchListener {
                override fun onStartTrackingTouch(slider: Slider) {
                    // 滑块开始被触摸时的逻辑
                }

                override fun onStopTrackingTouch(slider: Slider) {
                    // 滑块停止滑动（放开）时触发的逻辑
                    val process = slider.value
                    _yongHuJiDingYiViewModel.calSliderChanged(process, false)
                }
            })

            _binding.atDetailBeforeCommit.setOnClickListener {
                _yongHuJiDingYiViewModel.requestSaveShenQing()

                //
                addTouch(type = "detail_before_commit_click")
            }

        } catch (e: Exception) {
            //
        }
    }

    private fun configUIData() {
        _yongHuJiDingYiViewModel.requestYongHuJiDingYi()
    }

    private fun updateCommitUIState() {
        if (_yongHuJiDingYiViewModel.decideJinE <= 0) {
            _binding.atDetailBeforeCommit.isEnabled = false
            _binding.atDetailBeforeCommit.setTextColor(Color.parseColor("#FFFFFF"))
            _binding.atDetailBeforeCommit.setBackgroundResource(R.drawable.layer_c25_dedede)
        } else {
            _binding.atDetailBeforeCommit.isEnabled = true
            _binding.atDetailBeforeCommit.setTextColor(Color.parseColor("#BEFF6A"))
            _binding.atDetailBeforeCommit.setBackgroundResource(R.drawable.layer_c25_000000)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setCutDownStart() {
        var curTick = 5
        try {
            _guideTimer.cancel()
            _guideTimer = Timer()
            _guideTimer.schedule(object : TimerTask() {
                override fun run() {
                    runOnUiThread {
                        _binding.atDetailBeforeGuideSeconds.text = "${curTick}s"

                        if (curTick == 0) {
                            _guideTimer.cancel()
                            _binding.atDetailBeforeGuideSeconds.visibility = View.GONE
                            _binding.atDetailBeforeGuideOk.visibility = View.VISIBLE
                        }
                        curTick -= 1
                    }
                }
            }, 0, 1000)
        } catch (e: Exception) {
            //
        }
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}

